package java8.atguigu.teacher.forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 * @program lambda
 * @description:
 * @author: zhanglu
 * @create: 2019-05-27 23:08:00
 * 递归
 */
public class Calculate extends RecursiveTask<Long> {

    private long start;
    private long end;
    private static final long temp = 10000;

    public Calculate(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        long len = end - start;
        if(len <= temp){
            long sum = 0;
            for(long i = start; i <= end; i++){
                sum += i;
            }
            return sum;
        }else {
            long middle = (start + end) / 2;
            Calculate left = new Calculate(start, middle);
            left.fork();    //拆分自任务，同时压入线程队列

            Calculate right = new Calculate(middle + 1, end);
            right.fork();

            return left.join() + right.join();
        }
    }
}
